import router from '@system.router'
import storage from '@system.storage'
import fetch from '@system.fetch'
import md5 from "/src/global/md5.js";
import prompt from '@system.prompt'
function start(){
  console.log(router.getPages());
}
function redirect(uri,params){
  if(uri === 'back'){
    router.back();
  }else{
    router.push({
      uri: uri,
      params: params
    })
  }
}

// 同步获取缓存数据
 async function cget(key){
    let rs = false;
    let data = await storage.get({key: key});
    console.log('data2'+key,data);
    if(data.data){
      data = data.data;
      data = JSON.parse(data);
      if(!data.isExpire){
        rs = data.data; 
      }else{
        var timestamp = Date.now();
        if(data.expire - timestamp >= 0){
          rs = data.data;
        } 
      }
    }
    return rs;
}

  async function ccget(key) {
    let rs = await storage.get({key: key});
    console.log('rs',rs);
    return rs;
  
}

async function cset(key,data,outTime){
   console.log('data1'+key);
    outTime = outTime?outTime:0;
    let isExpire = outTime !== 0;
    var timestamp = Date.now();
    var cacheData = {isExpire:isExpire,expire:timestamp + outTime*1000,data:data};
    await storage.set({
        key: key,
        value: cacheData,
        success: function(data) {
          // console.log('handling successs')
        },
        fail: function(data, code) {
          // console.log(`handling fail, code = ${code}`)
        }
      })
}
async function userToken(){
  let cache = await $xt.cget('utoken');
  if(!cache){
    let timestamp = Date.now();
    let uinfo = {uid:Math.random().toString(36).substr(2),utime:parseInt((timestamp/1000).toString()),coins:0}
    cset('utoken',uinfo);
    $xConfig.uinfo = uinfo;
  }else{
    $xConfig.uinfo = cache;
  }  
}
function getSignParams(params){
  let ts = Math.round(new Date().getTime()/1000).toString();
  let sign = ts.substr(-4);
  const authParam = {"ts":ts,"sign":md5.hex_md5(sign)}
  return Object.assign(params,authParam);
}
// request get请求
async  function rfetch(path,params){
  userToken();
  let url = path.includes('http')? path: $xConfig.rootHost+path;
  let requestParams = {
    uuid: $xConfig.uinfo.uid,
    app_name: $xConfig.appName,
    current_page:'',
    app_version:$xConfig.appVersion,
    utime:$xConfig.uinfo.utime
  };
  requestParams = Object.assign(requestParams,params)
  let resData = {code:0,data:''};
  let response = await  fetch.fetch({
    url: url,
    data:getSignParams(requestParams),
    responseType: 'json'
  });
  if(response.data.code == 200){
    resData = response.data.data;
  }
  return resData;
}

function objToArr(obj){
  let nList = [];
  for(var i in obj){
    if(i !== undefined  && obj[i] !== {}){
      nList.push(obj[i]);
    }
  }
  return nList;
}
function toast(msg){
  prompt.showToast({
    message: msg
  })
}
async function userCoinsRecord(coins,remark){
  var userInfo = await this.getUserInfo();
  console.log('userInfo',userInfo);
  coins = parseInt(coins);
  if(!userInfo.coins){
    userInfo.coins = 0;
  }
  userInfo.coins = userInfo.coins + coins;
  if(userInfo.coins < 50000){
      this.setUserInfo(userInfo);
      var xCoinsRecord = await this.cget('xCoinsRecord');
      xCoinsRecord = xCoinsRecord?xCoinsRecord:[];
      var time = Date.now();
      var row = {coins:coins,remark:remark,time:time};
      xCoinsRecord.push(row)
      this.cset('xCoinsRecord',xCoinsRecord);
  }
}
async function setUserInfo(userInfo){
  this.cset('utoken',userInfo);
}
async function getUserInfo(){
  let userInfo = {};
  let cacheUserInfo = await $xt.cget('utoken');
  if(cacheUserInfo){
    userInfo = cacheUserInfo;
  }
  return cacheUserInfo;
}
// 时间戳转换成日期时间
function timestampToDate(timestamp) {
  var date = new Date(timestamp); // 时间戳转换成Date对象
  var year = date.getFullYear(); // 获取年份
  var month = date.getMonth() + 1; // 获取月份，需要+1因为月份从0开始
  var day = date.getDate(); // 获取日
  // 格式化月份、日期、小时、分钟和秒
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  // 组合成日期时间字符串
  return year + '.' + month + '.' + day;
}
// 时间戳转换成日期时间
function timestampToDateTime(timestamp) {
  var date = new Date(timestamp); // 时间戳转换成Date对象
  var year = date.getFullYear(); // 获取年份
  var month = date.getMonth() + 1; // 获取月份，需要+1因为月份从0开始
  var day = date.getDate(); // 获取日
  var hours = date.getHours(); // 获取小时
  var minutes = date.getMinutes(); // 获取分钟
  var seconds = date.getSeconds(); // 获取秒钟

  // 格式化月份、日期、小时、分钟和秒
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;
  hours = hours < 10 ? '0' + hours : hours;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  seconds = seconds < 10 ? '0' + seconds : seconds;

  // 组合成日期时间字符串
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
// 给金币
export default {
  userToken,redirect,cget,cset,rfetch,ccget,objToArr,toast,userCoinsRecord,setUserInfo,getUserInfo,timestampToDateTime,timestampToDate
}
